<?php

namespace app\admin\controller;

use app\model\CardItemModel;
use app\model\CardModel;
use support\Request;
use support\Response;
use Exception;

/**
 * 卡数据管理控制器
 * 
 * @package app\admin\controller
 */
class CardItemController
{
    /**
     * 获取卡数据列表
     * 
     * @param Request $request 请求对象
     * @return Response
     */
    public function index(Request $request): Response
    {
        try {
            $cardId = $request->get('card_id');
            $page = (int)$request->get('page', 1);
            $limit = (int)$request->get('limit', 20);
            
            if (empty($cardId)) {
                throw new Exception('卡ID不能为空');
            }

            $query = CardItemModel::where('card_id', $cardId);
            
            // 状态筛选
            if ($request->get('status') !== null) {
                $query->where('status', $request->get('status'));
            }
            
            // 卡号搜索
            if ($request->get('card_number')) {
                $query->where('card_number', 'like', '%' . $request->get('card_number') . '%');
            }

            if ($request->get('sort') && $request->get('order')) {
                $query->orderBy($request->get('sort'), $request->get('order'));
            }

            $total = $query->count();
            $items = $query->offset(($page - 1) * $limit)
                          ->limit($limit)
                          ->get();

            // 处理数据
            $data = [];
            foreach ($items as $item) {
                $data[] = [
                    'id' => $item->id,
                    'card_id' => $item->card_id,
                    'card_no' => $item->card_no,
                    'card_number' => $item->card_number,
                    'beauty_card_number' => $item->beautifyCardNumber(),
                    'expired_days' => $item->expired_days,
                    'status' => $item->status,
                    'status_text' => CardItemModel::getStatusText($item->status),
                    'score' => $item->score,
                    'use_score' => $item->use_score,
                    'created_at' => $item->created_at,
                    'updated_at' => $item->updated_at
                ];
            }

            return json([
                'data' => [
                    'list' => $data,
                    'total' => $total,
                    'page' => $page,
                    'limit' => $limit
                ],
                'msg' => '获取成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 创建单个卡数据
     * 
     * @param Request $request 请求对象
     * @return Response
     */
    public function store(Request $request): Response
    {
        try {
            $cardId = $request->post('card_id');
            $cardNo = $request->post('card_no');
            $cardNumber = $request->post('card_number');
            $expiredAt = $request->post('expired_days', 0);
            $score = $request->post('score', 0);

            // 参数验证
            if (empty($cardId)) {
                throw new Exception('卡ID不能为空');
            }

            // 验证卡是否存在
            $card = CardModel::find($cardId);
            if (!$card) {
                throw new Exception('卡不存在');
            }

            // 生成卡号和卡密（如果未提供）
            if (empty($cardNo)) {
                $cardNo = CardItemModel::generateCardNo();
            }
            if (empty($cardNumber)) {
                $cardNumber = CardItemModel::generateCardNumber();
            }

            // 检查卡号是否已存在
            $existingCard = CardItemModel::where('card_no', $cardNo)->first();
            if ($existingCard) {
                throw new Exception('卡号已存在');
            }

            $cardItem = new CardItemModel();
            $cardItem->card_id = $cardId;
            $cardItem->card_no = $cardNo;
            $cardItem->card_number = $cardNumber;
            $cardItem->expired_days = $expiredAt;
            $cardItem->status = CardItemModel::STATUS_UNUSED;
            $cardItem->score = $score;
            $cardItem->created_at = time();
            $cardItem->updated_at = time();

            if (!$cardItem->save()) {
                throw new Exception('创建卡数据失败');
            }

            return json([
                'data' => [
                    'id' => $cardItem->id,
                    'card_no' => $cardItem->card_no,
                    'card_number' => $cardItem->card_number
                ],
                'msg' => '创建成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 批量生成卡数据
     * 
     * @param Request $request 请求对象
     * @return Response
     */
    public function batchGenerate(Request $request): Response
    {
        try {
            $cardId = $request->post('card_id');
            $count = (int)$request->post('count', 1);
            $expiredAt = $request->post('expired_days', 0);
            $score = $request->post('score', 0);

            // 参数验证
            if (empty($cardId)) {
                throw new Exception('卡ID不能为空');
            }
            if ($count <= 0 || $count > 1000) {
                throw new Exception('生成数量必须在1-1000之间');
            }

            // 验证卡是否存在
            $card = CardModel::find($cardId);
            if (!$card) {
                throw new Exception('卡不存在');
            }

            $currentTime = time();

            for ($i = 0; $i < $count; $i++) {
                // 生成唯一的卡号
                do {
                    $cardNo = CardItemModel::generateCardNo();
                    $existingCard = CardItemModel::where('card_no', $cardNo)->first();
                } while ($existingCard);

                $cardItem = new CardItemModel();
                $cardItem->card_id = $cardId;
                $cardItem->card_no = $cardNo;
                $cardItem->card_number = CardItemModel::generateCardNumber();
                $cardItem->expired_days = $expiredAt;
                $cardItem->status = CardItemModel::STATUS_UNUSED;
                $cardItem->score = $score;
                $cardItem->created_at = $currentTime;
                $cardItem->updated_at = $currentTime;

                if (!$cardItem->save()) {
                    throw new Exception('批量生成卡数据失败');
                }
            }

            return json([
                'msg' => '批量生成成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 删除卡数据
     * 
     * @param Request $request 请求对象
     * @param int $id 卡数据ID
     * @return Response
     */
    public function destroy(Request $request, int $id): Response
    {
        try {
            $cardItem = CardItemModel::find($id);
            if (!$cardItem) {
                throw new Exception('卡数据不存在');
            }

            // 检查是否已被使用
            if ($cardItem->status == CardItemModel::STATUS_USED) {
                throw new Exception('已使用的卡数据不能删除');
            }

            if (!$cardItem->delete()) {
                throw new Exception('删除失败');
            }

            return json([
                'data' => null,
                'msg' => '删除成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 批量删除卡数据
     * 
     * @param Request $request 请求对象
     * @return Response
     */
    public function batchDestroy(Request $request): Response
    {
        try {
            $ids = $request->post('ids');
            
            if (empty($ids) || !is_array($ids)) {
                throw new Exception('请选择要删除的卡数据');
            }

            // 检查是否有已使用的卡数据
            $usedCards = CardItemModel::whereIn('id', $ids)
                                    ->where('status', CardItemModel::STATUS_USED)
                                    ->count();
            if ($usedCards > 0) {
                throw new Exception('选中的卡数据中包含已使用的卡，无法删除');
            }

            $deletedCount = CardItemModel::whereIn('id', $ids)->delete();
            if ($deletedCount == 0) {
                throw new Exception('删除失败');
            }

            return json([
                'data' => [
                    'deleted_count' => $deletedCount
                ],
                'msg' => '批量删除成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 更新卡数据
     * 
     * @param Request $request 请求对象
     * @param int $id 卡数据ID
     * @return Response
     */
    public function update(Request $request, int $id): Response
    {
        try {
            $cardItem = CardItemModel::find($id);
            if (!$cardItem) {
                throw new Exception('卡数据不存在');
            }

            // 检查是否已被使用
            if ($cardItem->status == CardItemModel::STATUS_USED) {
                throw new Exception('已使用的卡数据不能修改');
            }

            $cardNo = $request->post('card_no');
            $cardNumber = $request->post('card_number');
            $expiredAt = $request->post('expired_days');
            $score = $request->post('score');

            // 如果修改卡号，检查是否重复
            if (!empty($cardNo) && $cardNo !== $cardItem->card_no) {
                $existingCard = CardItemModel::where('card_no', $cardNo)
                                           ->where('id', '!=', $id)
                                           ->first();
                if ($existingCard) {
                    throw new Exception('卡号已存在');
                }
                $cardItem->card_no = $cardNo;
            }

            if (!empty($cardNumber)) {
                $cardItem->card_number = $cardNumber;
            }
            if ($expiredAt !== null) {
                $cardItem->expired_days = $expiredAt;
            }
            if ($score !== null) {
                $cardItem->score = $score;
            }

            $cardItem->updated_at = time();

            if (!$cardItem->save()) {
                throw new Exception('更新失败');
            }

            return json([
                'data' => [
                    'id' => $cardItem->id,
                    'card_no' => $cardItem->card_no,
                    'card_number' => $cardItem->card_number,
                    'expired_days' => $cardItem->expired_days,
                    'score' => $cardItem->score
                ],
                'msg' => '更新成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 获取卡数据详情
     * 
     * @param Request $request 请求对象
     * @param int $id 卡数据ID
     * @return Response
     */
    public function show(Request $request, int $id): Response
    {
        try {
            $cardItem = CardItemModel::find($id);
            if (!$cardItem) {
                throw new Exception('卡数据不存在');
            }

            $data = [
                'id' => $cardItem->id,
                'card_id' => $cardItem->card_id,
                'card_no' => $cardItem->card_no,
                'card_number' => $cardItem->card_number,
                'expired_days' => $cardItem->expired_days,
                'status' => $cardItem->status,
                'status_text' => CardItemModel::getStatusText($cardItem->status),
                'score' => $cardItem->score,
                'created_at' => $cardItem->created_at,
                'updated_at' => $cardItem->updated_at
            ];

            return json([
                'data' => $data,
                'msg' => '获取成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }
}
